package controller.base;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import core.modules.base.entity.SysMenu;
import core.modules.base.entity.SysUser;
import core.modules.base.service.SysMenuService;
import core.modules.base.service.SysUserService;
import core.util.AjaxResult;
import core.util.WebUtil;

@Controller
public class SysController {
	Logger LOGGER = LoggerFactory.getLogger(SysController.class);

	@Autowired
	SysMenuService sysMenuService;
	@Autowired
	SysUserService sysUserService;

	@Autowired
	FreeMarkerConfigurer freeMarkerConfigurer;



	@RequestMapping("/")
	public Object blank(HttpServletRequest request, HttpServletResponse response, ModelMap map) {
		return "redirect:index.htm";
	}

	@RequestMapping("index.htm")
	// @RequiresPermissions("add")
	public Object index(HttpServletRequest request, HttpServletResponse response, ModelMap map) {
		SysUser user = WebUtil.getUser();
		String roleid = sysUserService.getDao().getRoleIds(user.getId()).get(0);
		List<SysMenu> menus = sysMenuService.getDao().findListByRoleId(roleid);
		menus = setChildData(menus);
		map.put("menus", menus);
		return "base/index";
	}

	public List<SysMenu> setChildData(List<SysMenu> list) {
		Map<String, SysMenu> map = new HashMap<>();
		List<SysMenu> result =new ArrayList<>();
		for (SysMenu sysMenu : list) {
			sysMenu.setChildren(new ArrayList<>());
			map.put(sysMenu.getId(), sysMenu);
			if (sysMenu.getPid().equals("0")) {
				result.add(sysMenu);
			}
		}
		for (SysMenu sysMenu : list) {
			SysMenu temp = map.get(sysMenu.getPid());
			if (temp != null) {
				temp.getChildren().add(sysMenu);
			}
		}
		return result;
	}

	@RequestMapping(value = "login.htm")
	public Object login(UsernamePasswordToken token, HttpServletRequest request, HttpServletResponse response,
			ModelMap map) {
		
		System.out.println(request.getRequestURI());
		try {
			if (token != null && token.getUsername() != null && token.getPassword() != null) {
				Subject subject = SecurityUtils.getSubject(); // 获取Subject单例对象
				subject.login(token); // 登陆
				return "redirect:index.htm";
			}
		} catch (Exception e) {
			map.put("errMsg", e.getMessage());
		}
		return "base/login";
	}

	@RequestMapping("logout.htm")
	public Object logout(HttpServletRequest request, HttpServletResponse response, ModelMap map) {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return "base/login";
	}

	@RequestMapping("auth.htm")
	public Object auth(HttpServletRequest request, HttpServletResponse response, ModelMap map) {
		String username = WebUtil.getStr("username", request);
		String password = WebUtil.getStr("password", request);
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);

		Subject subject = SecurityUtils.getSubject(); // 获取Subject单例对象
		subject.login(token); // 登陆
		return "base/login";
	}

	@RequestMapping("upload.json")
	@ResponseBody
	public AjaxResult fileUpload(HttpServletRequest request, HttpServletResponse response) {
		AjaxResult ajaxResult = null;
		try {
			CommonsMultipartResolver cmr = new CommonsMultipartResolver(request.getServletContext());
			Assert.isTrue(cmr.isMultipart(request), "非Multipart请求");
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			Iterator<String> iter = multiRequest.getFileNames();
			String uploadfilePath = WebUtil.getProperties("uploadfile.path");
			String uploadfileUrl = WebUtil.getProperties("uploadfile.url");
			while (iter.hasNext()) {
				// 取得上传文件
				MultipartFile file = multiRequest.getFile(iter.next());
				Assert.isTrue(file != null && !file.isEmpty(), "上传文件为空");
				ajaxResult = new AjaxResult();
				
				Map<String, String> data = new HashMap<String, String>();
				ajaxResult.setData(data);
				String filename = file.getOriginalFilename();
				String extension = filename.substring(filename.lastIndexOf("."));
				String name = WebUtil.UUID() + extension;
				String dataFloder = WebUtil.getDateStr("/yyyy/MM/dd", new Date());
				String filepath = dataFloder + "/" + name;
				data.put("oriName", filename);
				data.put("ext", extension);
				data.put("name", name);
				data.put("path", filepath);
				data.put("url", uploadfileUrl + filepath);
				File floder = new File(uploadfilePath + dataFloder);
				if (!floder.exists()) {
					floder.mkdirs();
				}
				file.transferTo(new File(floder.getAbsolutePath() + "/" + name));
			}
		} catch (Exception e) {
			ajaxResult = new AjaxResult(false, e.getMessage());
		}
		return ajaxResult;
	}
}
